#include <stdio.h>
#include <pthread.h>

// 定义一个读写锁变量
pthread_rwlock_t rwlock;

// 共享数据
int shared_data = 0;

// 读线程函数
void* reader(void* arg) {
    pthread_rwlock_rdlock(&rwlock); // 获取读锁
    printf("Reader thread %ld: shared_data = %d\n", pthread_self(), shared_data);
    pthread_rwlock_unlock(&rwlock); // 释放读锁
    pthread_exit(NULL);
}
// 写线程函数
void* writer(void* arg) {
    pthread_rwlock_wrlock(&rwlock); // 获取写锁
    shared_data++; // 修改共享数据
    printf("Writer thread %ld: shared_data = %d\n", pthread_self(), shared_data);
    pthread_rwlock_unlock(&rwlock); // 释放写锁
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[4];
    
    // 初始化读写锁
    pthread_rwlock_init(&rwlock, NULL);
    
    // 创建2个读线程和2个写线程
    for (int i = 0; i < 2; i++) {
        pthread_create(&threads[i], NULL, reader, NULL);
        pthread_create(&threads[i+2], NULL, writer, NULL);
    }
    
    // 等待线程结束
    for (int i = 0; i < 4; i++) {
        pthread_join(threads[i], NULL);
    }
    
    // 销毁读写锁
    pthread_rwlock_destroy(&rwlock);
    
    return 0;
}
